import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from './user.entity';
import { Logs } from '../logs/logs.entity';
import { getUserDto } from './dto/get-user.dto';
import { conditionUtils } from '../utils/db.helper';

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User) private readonly userRepository: Repository<User>,
    @InjectRepository(Logs) private readonly logsRepository: Repository<Logs>,
  ) {}

  findAll(query: getUserDto) {
    const { limit, page = 1, username, gender, role } = query;
    const take = limit || 10;
    const skip = (page - 1) * take;

    /* return this.userRepository.find({
      select: {
        id: true,
        username: true,
        profile: {
          gender: true,
        },
      },
      relations: {
        profile: true,
        roles: true,
      },
      where: {
        username,
        profile: {
          gender,
        },
        roles: {
          id: role,
        },
      },
      take,
      skip,
    }); */

    const queryBuilder = this.userRepository
      .createQueryBuilder('user')
      .leftJoinAndSelect('user.profile', 'profile')
      .leftJoinAndSelect('user.roles', 'roles');

    /* if (username) {
      queryBuilder.where('user.username = :username', { username });
    } else {
      queryBuilder.where('user.username IS NOT NULL');
    }
    if (gender) {
      queryBuilder.andWhere('profile.gender = :gender', { gender });
    } else {
      queryBuilder.andWhere('profile.gender IS NOT NULL');
    }
    if (role) {
      queryBuilder.andWhere('roles.id = :role', { role });
    } else {
      queryBuilder.andWhere('roles.id IS NOT NULL');
    } */
    /* queryBuilder.andWhere(username ? 'user.username = :username' : '1=1', {
      username,
    }); */
    const obj = {
      'user.username': username,
      'profile.gender': gender,
      'roles.id': role,
    };
    /* Object.keys(obj).forEach((key) => {
      if (obj[key]) {
        queryBuilder.andWhere(`${key} = :${key}`, { [key]: obj[key] });
      }
    }); */
    const nweQuery = conditionUtils(queryBuilder, obj);

    return nweQuery.take(take).skip(skip).getMany();
  }

  find(username: string) {
    return this.userRepository.findOne({ where: { username } });
  }

  findOne(id: number) {
    return this.userRepository.findOne({ where: { id } });
  }

  create(user: User) {
    const userTmp = this.userRepository.create(user);
    return this.userRepository.save(userTmp);
  }

  update(id: number, user: Partial<User>) {
    return this.userRepository.update(id, user);
  }

  remove(id: number) {
    return this.userRepository.delete(id);
  }

  findProfile(id: number) {
    return this.userRepository.findOne({
      where: {
        id,
      },
      relations: {
        profile: true,
      },
    });
  }

  async findUserLogs(id: number) {
    const user = await this.findOne(id);

    return this.logsRepository.find({
      where: {
        user,
      },
      relations: {
        user: true,
      },
    });
  }

  getLogsByGroup(id: number) {
    return (
      this.logsRepository
        .createQueryBuilder('logs')
        .select('logs.result', 'result')
        .addSelect('COUNT("logs.result")', 'count')
        .leftJoinAndSelect('logs.user', 'user')
        .where('user.id = :id', { id })
        .groupBy('logs.result')
        // .orderBy('result', 'DESC')
        .orderBy('count', 'DESC')
        .addOrderBy('result', 'DESC')
        .offset(2)
        .limit(3)
        .getRawMany()
    );

    // return this.logsRepository.query('SELECT * FROM logs');
  }

  async getUser() {
    return {
      code: 200,
      data: [],
      message: '请求成功了',
    };
  }
  addUser() {
    return {
      code: 200,
      data: {},
      message: '添加成功了',
    };
  }
}
